package com.wuliang.blog.core.basic;

import com.google.gson.annotations.Expose;
import com.wuliang.blog.utils.ClassUtils;
import com.wuliang.blog.utils.JPAUtils;
import com.wuliang.blog.utils.JsonUtils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.data.jpa.domain.Specification;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

@Data
public abstract class BaseVo<T extends BasicEntity> implements Serializable {

    @ApiModelProperty(name = "pageNo", value = "显示的第几页", dataType = "int")
    private Integer pageNo = 1;

    @ApiModelProperty(name = "pageSize", value = "每页显示条目数", dataType = "int")
    private Integer pageSize = 10;

    @Expose(serialize = false, deserialize = false)
    @ApiModelProperty(name = "searchKeywords", value = "要搜索的关键字对象", dataType = "object")
    private Map<String, Object> searchKeywords = new LinkedHashMap<>();

    @Expose(serialize = false, deserialize = false)
    @ApiModelProperty(name = "searchFuzzyKeyword", value = "模糊关键字查询", dataType = "string")
    private Map<String, Object> searchFuzzyKeyword = new LinkedHashMap<>();

    @Expose
    @ApiModelProperty(name = "sortedField", value = "排序的关键字", dataType = "string")
    private String sortedField;

    public void checkSearchKeywords() {
        if (searchKeywords.isEmpty() || searchKeywords.get("dataStatus") == null) {
            searchKeywords.put("dataStatus", 0);
        }
        Map<String, Object> thisMap = JsonUtils.objectToMap(this);
        searchKeywords.putAll(thisMap);
        String entityName = this.getClass().getSimpleName();
        String primerKeyName =
                ((char) (entityName.charAt(0) + 32)) + entityName.substring(1, entityName.length() - 2) + "Id";
        Object idValue = ClassUtils.invokeGetMethod(this);
        if (idValue != null && !idValue.equals(0)) {
            searchKeywords.put("ID", Integer.parseInt(idValue.toString()));
        }
        searchKeywords.remove(primerKeyName);
    }

    public Specification<T> toSpecification() {
        checkSearchKeywords();
        return JPAUtils.getFields(searchKeywords, searchFuzzyKeyword);
    }

}
